package Beans.controllers;

import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import Beans.UserBean;

import step4.dao.fabric.DaoFabric;
import step4.dao.instance.UserDao;
import step4.model.LoginBean;

@ManagedBean
@ApplicationScoped // Utilisation de application scope afin d'offrir un point d'entr�e unique � l'ensemble des clients
public class UserBeanController {
	private UserDao userDao;
	
	public UserBeanController() {
		this.userDao=DaoFabric.getInstance().createUserDao();
	}
	
	public String registerUser(UserBean userSubmitted){
		this.userDao.addUser(userSubmitted);
		return "../vue/activites.jsf";
	}

	public void login(LoginBean loginSubmitted){		
		UserBean user = this.userDao.checkUser(loginSubmitted.getLogin(), loginSubmitted.getPwd());
		
		if( user!=null){
			ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
			Map<String, Object> sessionMap = externalContext.getSessionMap();
			
			sessionMap.put("loggedUser", user);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Connection OK", ""));
		}else{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL,"Connection fail", ""));
		}
	}
	
	public void logout() {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		
		System.out.println("logout");
		sessionMap.remove("loggedUser");
	}
}
